#Copyright Ken Faulkner 2007.
import htmllib
import formatter
from Datatypes.AudioDetails  import AudioDetails
import traceback
from Common.logRoutine import *


class HTMLParse(htmllib.HTMLParser):

  def __init__(self, formatter, verbose=0):
    htmllib.HTMLParser.__init__(self, formatter, verbose)

    self.linkList = []
    self.buffer = ""
    self.latestAudioDetail = None

    self.log = getLogger()
    
  def start_a(self, attrs):
    for i in attrs:
      if i[0] == "href":
        idx = i[1].find('rams')
        if idx != -1:
          self.latestAudioDetail = AudioDetails()
          self.latestAudioDetail.link = i[1]
          
          # should have been the previous <strong> entry.
          self.latestAudioDetail.time = self.getDuration( self.buffer )
          
  def start_strong(self, attrs):
    self.buffer = ""
    
  def end_strong(self):
    if self.latestAudioDetail != None:
      self.latestAudioDetail.title = self.buffer
      self.buffer = ""

  def getDuration( self, data ):
    """
    Calculates the duration (in minutes) given a piece of text.
    @param data  String, eg. 13:30-13:45
                             04:00-04:30
                             
                             etc
    """
    
    duration = None
    
    try:
      if data != None:
        sp = data.split("-")
        
        # we get 2 times.
        if len( sp ) == 2:
          time1 = sp[0].split(":")
          time2 = sp[1].split(":")
          
          hour1 = int( time1[0] )
          minute1 = int( time1[1] )
          
          hour2 = int( time2[0] )
          minute2 = int( time2[1] )
          
          dur = ( hour2 * 60 + minute2 ) - ( hour1 * 60 + minute1 )

          duration = dur
        
    except:
      self.log.error("getDuration  exception " + traceback.format_exc() )
    
    return duration
    
  def getEpisode( self, data ):
    """
    Detect episode # info.
    Basic detection and not fool proof, but worth a shot.
    """
    
    epNo = 0
    
    self.log.debug("getEpisode " + data )
    
    lowerData = data.lower()
    
    self.log.debug("lower " + lowerData )
    
    idx = lowerData.find("episode")
    if idx != -1:
    
      self.log.debug("FOUND EPISODE")
      d = lowerData[idx:]
      sp = d.split()
      
      self.log.debug("SP is " + str( sp ) )
      
      if sp[0] == "episode" and sp[2] == 'of':
        epNo = int( sp[1] )
        
    
    self.log.debug("epno " + str( epNo ) )
    
    return epNo
    
  def handle_data(self, data):
    self.buffer += data
    
    # if we have latestAudioDetail then append this as the description.
    # then reset LAD to be None... that way we wont try and append any data that is not
    # the description.
    if self.latestAudioDetail != None and self.latestAudioDetail.title != None:
  
      self.latestAudioDetail.description = data
      
      self.latestAudioDetail.episode_no = self.getEpisode( data )
      
      self.linkList.append(self.latestAudioDetail)
      self.latestAudioDetail = None
      

def extractLinksFromHTML( data ):

  parser = None
  try:

    myWriter = formatter.DumbWriter()
    myFormatter = formatter.AbstractFormatter(myWriter)
    #myParser = htmllib.HTMLParser(myFormatter)

    parser = HTMLParse(myFormatter)

    try:
      # process the data file and put into lucene.
      parser.feed(data)

    except:
      self.log.warning("extractLinksFromHTML inner exception "+traceback.format_exc() )

  except:
    self.log.error("extractLinksFromHTML outer exception "+traceback.format_exc() )

  return parser.linkList


if __name__ == "__main__":

  
  data = open('monday.html').read()
  
  links = extractLinksFromHTML( data )

  for i in links:
    print i
  
  
